#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdio>
#include <strings.h>
#include <string.h>
#include "terminal.hpp"
using namespace std;

void Usage(string proName)
{
    cout << "\n\rUsage: " << proName << "[server IP] [server port]" << endl;
}

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    string serverIP;
};

// 定义用户套接字，不断收消息，将收到的消息放在buffer，然后再打印收到的消息
void *recv_message(void *args)
{

    ThreadData *td = static_cast<ThreadData *>(args);
    char buffer[1024];
    while (1) // 不断收消息
    {
        memset(buffer,0,sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t tlen = sizeof(temp);
        ssize_t s = recvfrom(td->sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &tlen);
        if (s > 0)
        {
            buffer[s] = '\0';
            cout << buffer << endl;
        }
    }
}

// 提示用户，获取用户信息，再将获取的用户信息发送
void *send_message(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    socklen_t len = sizeof(td->server);
    string msg;
    string welcome = td->serverIP;
    welcome += "coming...";
    sendto(td->sockfd, msg.c_str(), msg.size(), 0, (struct sockaddr *)&(td->server), len);
    while (1) // 不断发消息
    {
        cout << "Please Enter@ ";
        getline(cin, msg);
        sendto(td->sockfd, msg.c_str(), msg.size(), 0, (struct sockaddr *)&(td->server), len);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverIP = argv[1];
    uint16_t serverPort = stoi(argv[2]);

    struct ThreadData td;
    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_addr.s_addr = inet_addr(serverIP.c_str());
    td.server.sin_port = htons(serverPort);

    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        cout << "socker error" << endl;
        return 1;
    }
    td.serverIP = serverIP;
    // 客户端需要bind：客户端需要自己的IP和端口，否则服务器无法找到客户端。
    // 只不过不需要我们显式bind，一般由操作系统随机选择。
    // 注意：一个端口号只能被一个进程bind，堆server如此，对于client也是如此！
    // bind时机：首次发送数据时

    pthread_t recvr, sender;
    pthread_create(&recvr, nullptr, recv_message, (void *)&td);
    pthread_create(&sender, nullptr, send_message, (void *)&td);

    pthread_join(recvr, nullptr);
    pthread_join(sender, nullptr);

    close(td.sockfd);
    return 0;
}